package com.project.web.admin.controller.common;

import com.project.common.core.utils.exception.Result;
import com.project.common.core.utils.redis.RedisClient;
import com.project.common.core.utils.redis.RedisConsts;
import com.project.service.common.SMSService;
import com.project.web.admin.utils.CustomException;
import com.project.web.admin.utils.RESP_CODE_ENUM;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 后台公用controller
 */
@RestController("adminCommonController")
@RequestMapping("/admin/common")
public class CommonController extends BaseController {
    private static final long serialVersionUID = -7624305021416504596L;

    @Resource(name = "redisClient")
    private RedisClient redisClient;

    @Resource(name = "SMSServiceImpl")
    private SMSService smsService;

    /**
     * 短信验证码
     *
     * @param phone 手机号
     * @return
     */
    @ApiOperation(value = "通用短信验证码", notes = "通用短信验证码", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String")
    })
    @GetMapping(value = "/getPhoneCode")
    public Result<String> getPhoneCode(String phone) {
        // 查看redis中是否存在该手机号获取的验证码
        if (StringUtils.isNotBlank(redisClient.getString(RedisConsts.WXMEMBER_MOBILECODE_LIMIT_KEY + phone))) {
            throw new CustomException(RESP_CODE_ENUM.CAPTCHA_EXIST);
        }

        // 放入redis
        String captcha = RandomStringUtils.randomNumeric(6);
        redisClient.setAndExpire(RedisConsts.WXMEMBER_MOBILE_CAPTCHA + phone, captcha, RedisConsts.WXMEMBER_MOBILE_CAPTCHA_EXPIRE);
        smsService.sendAliSMSForFGeneral(phone, captcha);

        // 初始化返回参数
        return getResult("success");
    }

}
